import axios from 'axios'
import QS from 'qs';
import { Message as message } from 'element-ui';
const request = axios.create({
        baseURL: '',
        timeout: 5000
    }
)
request.interceptors.request.use(config => {
    let token = localStorage.getItem("token")
    config.headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': token,
    }
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use(
    response => {
        let data = response.data;
        console.log('response data-->', data);
        if (data.code == 0) {
            return Promise.resolve(data);
        } else {
            return Promise.reject(data);
        }
    }, error => {
        console.log('response error:', error + 'code:' + error.code)
        if (error.response.status == 401) {
            message({message: error.response.data.message})
            window.vue.$router.push({name: "login"});
            return
        }
        return Promise.reject(error.response.data);
    })


export function get(url, data) {
    return new Promise((resolve, reject) => {
        request.get(url, {params: data}).then(
            res => {
                resolve(res);
            }).catch(err => {
            reject(err)
        })
    });
}

export default request;

export function post(url, data) {
    return new Promise((resolve, reject) => {
        request.post(url, QS.stringify(data))
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err)
            })
    });
}
export function post_header(url, data,header) {
    return new Promise((resolve, reject) => {
        axios.post(url, QS.stringify(data),header)
            .then(res => {
                resolve(res);
            })
            .catch(err => {
                reject(err)
            })
    });
}

export function patch(url, data) {
    return new Promise((resolve, reject) => {
        request.patch(url, QS.stringify(data)).then(
            resp => {
                resolve(resp)
            }
        ).catch(err => {
            reject(err)
        });
    })
}

export function del(url, data) {

    return new Promise((resolve, reject) => {
        request.delete(url, QS.stringify(data)).then(
            resp => {
                resolve(resp)
            }
        ).catch(err => {
            reject(err)
        });
    })
}